package com.lin.util;

import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * 文件写入工具
 *
 * @author 九分石人, 2020-02-19
 */
@Slf4j
public class FileWriteUtil {


    /**
     * 判断文件是否存在，不存在则创建文件
     *
     * @param filePath 文件路径
     * @return 文件对象
     * @author com.lin, 2020-02-20
     */
    public static File canCreatFile(String filePath) {
        File file = new File(filePath);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return file;
    }


    /**
     * 将字符串内容写出到具体文件
     *
     * @param string   要写出的文件内容
     * @param filePath 要写出的文件路径
     * @author com.lin, 2020-02-19
     */
    public static void writeFromString(String string, String filePath) {
        File file = FileWriteUtil.canCreatFile(filePath);
        FileOutputStream outputStream = null;
        BufferedWriter writer = null;
        try {
            outputStream = new FileOutputStream(file);
            writer = new BufferedWriter(new OutputStreamWriter(outputStream));
            writer.write(string);
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }
    }

    /**
     * 将输入流内容写出到具体文件
     *
     * @param inputStream 要写出的输入流
     * @param filePath    要写出的文件路径
     * @author com.lin, 2020-02-20
     */
    public static void writeFromInputStream(InputStream inputStream, String filePath) {
        File file = FileWriteUtil.canCreatFile(filePath);
        FileOutputStream outputStream = null;
        try {
            byte[] b = new byte[1024];
            outputStream = new FileOutputStream(file);
            while (inputStream.read(b) > 0) {
                outputStream.write(b);
            }
        } catch (FileNotFoundException e) {
            log.error(e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage());
            }
        }

    }

}
